package com.atguigu.book.controller;

import com.atguigu.book.pojo.Cart;
import com.atguigu.book.pojo.User;
import com.atguigu.book.service.CartItemService;
import com.atguigu.book.service.UserService;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @ClassName: UserController
 * @Description:
 * @Author: wty
 * @Date: 2022/12/12
 */

public class UserController {
    private UserService userService;
    private CartItemService cartItemService;

    public String login(String uname, String pwd, HttpSession session) {
        User user = userService.login(uname, pwd);
        System.out.println("user = " + user);

        if (null != user) {
            // 加载购物车的信息
            Cart cart = cartItemService.getCart(user);
            user.setCart(cart);

            // 保存的user是加载了购物车信息的user
            session.setAttribute("currUser", user);
            // 加载价格查询
            session.setAttribute("minPrice", null);
            session.setAttribute("maxPrice", null);

            return "redirect:book.do";
        } else {
            return "user/login";
        }

    }


    public String regist(String uname, String pwd, String email, String verifyCode, HttpSession session, HttpServletResponse response) throws IOException {

        // 获取验证码
        Object kaptcha_session_key = session.getAttribute("KAPTCHA_SESSION_KEY");

        if (null == kaptcha_session_key || !verifyCode.equals((String) kaptcha_session_key)) {
            response.setCharacterEncoding("UTF-8");
            response.setContentType("text/html;charset=UTF-8");
            PrintWriter out = response.getWriter();
            //out.println("<script language = 'javascript'>'alert('验证码不正确!');window.location.href='page.do?operate=page&page=user/regist';</script>");
            out.println("<script language='javascript'>alert('验证码不正确！');</script>");
            return "user/regist";
        } else {
            if (verifyCode.equals((String) kaptcha_session_key)) {
                userService.registe(new User(uname, pwd, email, 0));
                return "user/login";
            }
        }

        return "user/login";

    }

    public String ckUname(String uname) {
        User user = userService.getUser(uname);
        if (null != user) {
            // 表示用户名已经被占用。不能注册
            return "json:{'uname':'1'}";
            //return "ajax:1";
        } else {
            // 用户名未查询到，可以注册
            return "json:{'uname':'0'}";
            //return "ajax:0";
        }
    }
}
